package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.SetmealEnableFailedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.SetmealService;
import com.sky.vo.DishItemVO;
import com.sky.vo.SetmealVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * 套餐业务实现
 */
@Service
@Slf4j
public class SetmealServiceImpl  extends ServiceImpl<SetmealMapper,Setmeal> implements SetmealService {

    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private DishMapper dishMapper;

    /**
     * 条件查询
     * @param setmeal
     * @return
     */
    public List<Setmeal> list(Setmeal setmeal) {
        List<Setmeal> list = lambdaQuery().eq(Setmeal::getCategoryId, setmeal.getCategoryId()).eq(Setmeal::getStatus, setmeal.getStatus()).list();
        return list;
    }

    /**
     * 根据id查询菜品选项
     * @param id
     * @return
     */
    public List<DishItemVO> getDishItemById(Long id) {
        return setmealMapper.getDishItemBySetmealId(id);
    }

    @Override
    public void saveWithDish(SetmealDTO setmealDTO) {
        //保存套餐信息
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);
        setmealMapper.insert(setmeal);
        //保存套餐关联菜品信息
        Long setMealId= setmeal.getId();
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> {
            setmealDish.setSetmealId(setMealId);
        });
        setmealDishMapper.insertBatch(setmealDishes);

    }

    @Override
    public PageResult pageQuery(SetmealPageQueryDTO setmealPageQueryDTO) {
        //添加分页查询参数
        Page <Setmeal> page = new Page<>(setmealPageQueryDTO.getPage(), setmealPageQueryDTO.getPageSize());
        page.addOrder(new OrderItem("create_time", false));

        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        //判断有没有传入查询条件
        String name=setmealPageQueryDTO.getName();
        Integer status=setmealPageQueryDTO.getStatus();
        Integer categoryId=setmealPageQueryDTO.getCategoryId();
        if (StringUtils.isBlank(name)&&status==null&&categoryId==null){
            Page<Setmeal> page1=page(page,queryWrapper);
            return new PageResult(page1.getTotal(),page1.getRecords());
        }
        queryWrapper.like(name!=null,Setmeal::getName,"%"+name+"%")
                    .eq(categoryId!=null,Setmeal::getCategoryId,categoryId)
                    .eq(status!=null,Setmeal::getStatus,status);
        Page<Setmeal> page1=page(page,queryWrapper);
        return new PageResult(page1.getTotal(),page1.getRecords());
    }

    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
        ids.forEach(id -> {
            if(setmealMapper.selectById(id).getStatus()==1){
                throw new DeletionNotAllowedException("套餐正在售卖中，无法删除");
            }
        });
        //删除套餐表中的数据
        setmealMapper.deleteBatchIds(ids);
        setmealDishMapper.delete(new LambdaQueryWrapper<SetmealDish>().in(SetmealDish::getSetmealId,ids));
    }

    @Override
    public SetmealVO getByIdWithDish(Long id) {
        //查询套餐
        Setmeal setmeal=setmealMapper.selectById(id);
        //查询关联菜品
        List<SetmealDish> setmealDishes=setmealDishMapper.selectList(new LambdaQueryWrapper<SetmealDish>().eq(SetmealDish::getSetmealId,id));
        //封装查询结果
        SetmealVO setmealVO=new SetmealVO();
        BeanUtils.copyProperties(setmeal, setmealVO);
        setmealVO.setSetmealDishes(setmealDishes);

        return setmealVO;
    }

    @Override
    @Transactional
    public void update(SetmealDTO setmealDTO) {
        //修改套餐
        Setmeal setmeal=new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);
        setmealMapper.updateById(setmeal);
        Long setmealId=setmealDTO.getId();
        //为每个菜品添加正确的setmealID
        List<SetmealDish> setmealDishes=setmealDTO.getSetmealDishes();
        if (setmealDishes != null && !setmealDishes.isEmpty()) {
            // 确保每个SetmealDish都有正确的setmealId
            setmealDishes.forEach(dish -> dish.setSetmealId(setmeal.getId()));
        }
        //删除套餐关联菜品信息
        setmealDishMapper.delete(new LambdaQueryWrapper<SetmealDish>().eq(SetmealDish::getSetmealId,setmealId));
        //添加套餐关联菜品信息
        if(!setmealDishes.isEmpty()) {
            setmealDishMapper.insertBatch(setmealDishes);
        }
    }

    @Override
    public void startOrStop(Integer status, Long id) {
        if(status== StatusConstant.ENABLE){
            //获取关联菜品信息
            List<SetmealDish> setmealDishes=setmealDishMapper.selectList(new LambdaQueryWrapper<SetmealDish>().eq(SetmealDish::getSetmealId,id));
            //获取关联菜品id
            List<Long> dishIds=setmealDishes.stream().map(SetmealDish::getDishId).collect(Collectors.toList());
            //判断菜品是否在售
            List<Dish> dishList=dishMapper.selectList(new LambdaQueryWrapper<Dish>().in(Dish::getId,dishIds).eq(Dish::getStatus,StatusConstant.ENABLE));
            if(dishList.size()!=dishIds.size()){
                throw new SetmealEnableFailedException(MessageConstant.SETMEAL_ENABLE_FAILED);
            }

        }
        Setmeal setmeal = Setmeal.builder()
                .id(id)
                .status(status)
                .build();
        setmealMapper.updateById(setmeal);
    }
}
